package com.dalei.vdsmanager.login.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.dalei.vdsmanager.security.dao.Role;
import com.dalei.vdsmanager.security.dao.User;
import com.dalei.vdsmanager.security.dao.UserDao;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginRedirectionAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5484271890325704269L;

	public static final String MANAGEMENT = "management";

	public static final String DETECTION = "detection";

	public static final String SELECTOR = "selector";

	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		Map<String, ?> session = ActionContext.getContext().getSession();
		String username = (String) session.get("SPRING_SECURITY_LAST_USERNAME");
		if (username != null) {
			User user = userDao.findUserByUserName(username);
			if (user != null) {
				Set<Role> roles = user.getRoles();
				List<String> roleNames = new ArrayList<String>();
				for (Role role : roles) {
					roleNames.add(role.getRoleName());
				}
				if (roleNames.contains("ROLE_ADMINISTRATOR")
						&& roleNames.contains("ROLE_USER")) {
					return SELECTOR;
				} else if (roleNames.contains("ROLE_ADMINISTRATOR")) {
					return MANAGEMENT;
				} else if (roleNames.contains("ROLE_USER")) {
					return DETECTION;
				} else {
					return NONE;
				}
			} else {
				return ERROR;
			}
		} else {
			return ERROR;
		}
	}

	@Override
	public void validate() {
		// TODO Auto-generated method stub
		super.validate();
	}
}
